<?php

namespace iBrand\Shop\Core\Listeners;

use iBrand\Component\Point\Model\Point;
use iBrand\Component\Refund\Service\RefundService;
use iBrand\Component\User\Models\User;
use iBrand\Shop\Core\Models\Refund;
use iBrand\Shop\Core\Models\ShopOrder;


/**
 * Created by PhpStorm.
 * User: eddy
 * Date: 2018/1/6
 * Time: 14:57
 */
class RefundEventListener
{
    protected $refundService;

    public function __construct(RefundService $refundService)
    {
        $this->refundService = $refundService;
    }


    public function onOrderRefundCompletePoint(Refund $refund)
    {
        if (!$refund OR $refund->status != Refund::STATUS_COMPLETE OR $refund->type == Refund::TYPE_EXCHANGE OR $refund->user_id == 934 OR $refund->user_id == 460) {
            return;
        }

        foreach ($refund->items as $item) {
            if (!Point::where('action', 'order_refund')->where('item_id', $item->order_item_id)->first()) {
                $shopOrder = ShopOrder::where('order_id', $refund->order->id)->first();
                $user = User::find($refund->user_id);
                if ($item->use_point) {    //如果使用了积分抵扣，用掉的积分需要返还
                    Point::create([
                        'user_id' => $refund->user_id,
                        'action' => 'order_refund',
                        'note' => '售后返还已使用积分',
                        'item_type' => 'iBrand\Component\Order\Models\OrderItem',
                        'item_id' => $item->order_item_id,
                        'value' => floor($item->orderItem->use_point / $item->orderItem->quantity * $item->quantity),
                        'status' => 1
                    ]);
                }

                //获得的积分需要扣除
                if ($point = Point::where('action', 'order_item')->where('item_id', $item->order_item_id)->first()) {
                    Point::create([
                        'user_id' => $refund->user_id,
                        'action' => 'order_item',
                        'note' => '售后扣除获得积分',
                        'item_type' => 'iBrand\Component\Order\Models\OrderItem',
                        'item_id' => $item->order_item_id,
                        'value' => -floor($point->value / $item->orderItem->quantity * $item->quantity),
                        'status' => 1]);
                }
            }
        }


    }

    public function subscribe($events)
    {
        $events->listen(
            'shop.refund.completed.point',
            'iBrand\Shop\Core\Listeners\RefundEventListener@onOrderRefundCompletePoint'
        );
    }
}